<?php

namespace App\Services\Service;

use App\Repositories\Criteria\Article\Authorid;
use App\Repositories\Criteria\Article\SearchCriteria;
use App\Repositories\Criteria\Article\Title;
use App\Repositories\Criteria\Common\TimeBetween;
use App\Services\Common\Service;
use App\Repositories\Model\ArticleRepository as Article;
use Illuminate\Support\Facades\Auth;

class ArticleService extends Service
{
    /**
     * @var Article
     */
    protected $article;

    /**
     * Repository
     *
     * ArticleService constructor.
     * @param Article $article
     */
    public function __construct(Article $article)
    {
        $this->article = $article;
        parent::__construct();
    }

    /**
     * @return Article
     */
    public function repository(){
        return $this->article;
    }

    /**
     * @param $request
     * @param int $rowNum
     * @return array
     */
    public function lists($request, $rowNum = 50){
        //where条件获取
        $where['title'] = $request->get('title', '');
        $where['start_time'] = $request->get('start_time', date('Y-m-d H:i:s', (time() - 10 * 86400)));
        $where['end_time'] = $request->get('end_time', date('Y-m-d H:i:s'));
        $where['author_id'] = $request->get('author_id', '');

        //获取模型数据
        if ( !empty($where['title']) )
        {
            $this->repository->pushCriteria(new Title($where['title']));
        }
        $this->repository->pushCriteria(new TimeBetween('pub_time', strtotime($where['start_time']), strtotime($where['end_time'])));
        if ( !empty($where['author_id']) && Auth::user()->is_admin )
        {
            $this->repository->pushCriteria(new Authorid($where['author_id']));
        }
        elseif( !Auth::user()->is_admin )
        {
            $this->repository->pushCriteria(new Authorid(Auth::user()->id));
        }
        //$this->repository->pushCriteria(new SearchCriteria($where));
        return ['list' => $this->repository->paginate($rowNum), 'where' => $where];
    }

    /**
     * @param $request
     * @return mixed
     */
    public function storeArticle($request){
        $data = $request->all();
        $data['pub_time'] = time();
        $data['author_id'] = Auth::user()->id;
        return $this->store($data);
    }

    /**
     * @param $request
     * @param $id
     * @return mixed
     */
    public function updateArticle($request, $id)
    {
        $data = $request->only(['title', 'intro', 'status', 'content']);
        if ($data['status'] == 1){
            $data['pub_time'] = time();
        }
        return $this->update($data,$id);
    }

    /**
     * @param $status
     * @param $rowNum
     * @return mixed
     */
    public function getFormalList($status, $rowNum){
        return $this->repository->getFormalList($status,$rowNum);
    }
}